package com.aiguigu.lottery.prize.listener;

import com.aiguigu.lottery.common.entity.PrizeRecordEntity;
import com.aiguigu.lottery.prize.service.PrizeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * 中奖消息监听器
 */
@Component
public class PrizeWinListener {
    
    private static final Logger logger = LoggerFactory.getLogger(PrizeWinListener.class);
    
    @Autowired
    private PrizeService prizeService;
    
    /**
     * 监听中奖消息
     */
    @RabbitListener(queues = "prize.win.queue")
    public void handlePrizeWinMessage(PrizeRecordEntity record) {
        try {
            logger.info("收到中奖消息: 用户ID={}, 奖品ID={}, 奖品名称={}", 
                       record.getUserId(), record.getPrizeId(), record.getPrizeName());
            
            // 验证消息内容
            if (record.getUserId() == null || record.getPrizeId() == null || record.getPrizeName() == null) {
                logger.error("中奖消息格式不正确，缺少必要字段: {}", record);
                return;
            }
            
            // 设置创建时间（如果没有设置）
            if (record.getCreateTime() == null) {
                record.setCreateTime(new Date());
            }
            
            // 保存中奖记录
            boolean result = prizeService.savePrizeRecord(record);
            
            if (result) {
                logger.info("通过消息队列成功保存中奖记录，用户ID: {}, 奖品: {}", 
                           record.getUserId(), record.getPrizeName());
            } else {
                logger.error("通过消息队列保存中奖记录失败，用户ID: {}, 奖品: {}", 
                            record.getUserId(), record.getPrizeName());
            }
            
        } catch (Exception e) {
            logger.error("处理中奖消息时发生异常: {}, 消息内容: {}", e.getMessage(), record, e);
            // 可以考虑将失败的消息发送到死信队列或重试队列
        }
    }

}